import random
from django.core.cache import cache
from backend.settings import DEBUG,EMAIL_HOST_USER
from rest_framework_simplejwt.tokens import RefreshToken
def is_phone(phone):
    """手机号校验，校验长度、数字和有效号段"""
    if len(phone) != 11 or not phone.isdigit():
        return False
    # 中国手机号有效号段: 13x, 14x, 15x, 16x, 17x, 18x, 19x
    valid_prefixes = ['13', '14', '15', '16', '17', '18', '19']
    return phone[:2] in valid_prefixes

def send_verification_code(target, scene='register'):
    """
    支持手机号/邮箱发送验证码
    :param target: 手机号或邮箱地址
    :param scene: 场景类型（'register'/'reset_pwd'）
    """
    # 生成验证码并存储（区分手机/邮箱场景）
    code = str(random.randint(100000, 999999))
    cache_key = f'verify_code_{scene}_{"phone" if is_phone(target) else "email"}_{target}'
    cache.set(cache_key, code, timeout=300)
    # 发送逻辑分离（手机号调用短信API，邮箱调用邮件服务）
    if is_phone(target):
       pass
    else:
        # 调用Django邮件模块（需配置settings.py中的EMAIL_*参数）
        from django.core.mail import send_mail
        send_mail(
            '密码重置验证码',
            f'您的验证码是：{code}',
            EMAIL_HOST_USER,
            [target],
            fail_silently=False,
            #auth_password='351116023a12eb'.encode('utf-8').decode('ascii', 'ignore')
        )
    return {'status': 'success', 'dev_code': code if DEBUG else None}

def verify_code(target, code, scene):
    """
    验证码校验（带自动清理和场景隔离）
    :return: (is_valid, error_msg)
    """
    cache_key = f'verify_code_{scene}_{"phone" if is_phone(target) else "email"}_{target}'
    cached_code = cache.get(cache_key)
    # 测试环境快捷验证
    if DEBUG and code == "123456":
        cache.delete(cache_key)
        return True, None
    
    if not cached_code or cached_code != code:
        return False, '验证码错误或已过期'
    
    cache.delete(cache_key)  # 验证成功后立即删除
    return True, None